<!-- 学生登录界面 -->
<template>
  <div class="wrap">
    <el-button id="openBtn">开启摄像头</el-button>
    <el-button id="exit" @click="cut()">↰</el-button>
    <div class="right">
      <video id="video" autoplay="autoplay"></video>
      <canvas id="canvas"></canvas>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import $ from "jquery";
import Vue from "../../../../main"

// import face from "../../../../utils/right";
import axios from "axios";
export default {
  name: "TeacherFace",
  data() {
    return {
      role: 2,
      labelPosition: "left",
      formLabelAlign: {
        username: "",
        password: "",
      },
    };
  },
  methods: {
    //用户登录请求后台处理
    login() {
      if (
        this.formLabelAlign.username == undefined ||
        this.formLabelAlign.username == ""
      ) {
        this.$message("请输入用户名");
        return;
      }
      if (
        !/^\d+$/.test(this.formLabelAlign.username) ||
        this.formLabelAlign.username.toString().length > 10
      ) {
        this.$message("用户名有误");
        return;
      }
      if (this.formLabelAlign.password == "") {
        this.$message("请输入密码");
        return;
      }
      this.$axios({
        url: `/api/login`,
        method: "post",
        data: {
          ...this.formLabelAlign,
        },
      }).then((res) => {
        let resData = res.data.data;
        if (resData != null) {
          switch (resData.role) {
            case "0": //管理员
              this.$cookies.set("cname", resData.adminName);
              this.$cookies.set("cid", resData.adminId);
              this.$cookies.set("role", 0);
              this.$router.push({ path: "/index" }); //跳转到首页
              break;
            case "1": //教师
              this.$cookies.set("cname", resData.teacherName);
              this.$cookies.set("cid", resData.teacherId);
              this.$cookies.set("role", 1);
              this.$router.push({ path: "/index" }); //跳转到教师用户
              break;
            case "2": //学生
              this.$cookies.set("cname", resData.studentName);
              this.$cookies.set("cid", resData.studentId);
              this.$router.push({ path: "/student" });
              break;
          }
        }
        if (resData == null) {
          //错误提示
          this.$message({
            showClose: true,
            type: "error",
            message: "用户名或者密码错误",
          });
        }
      });
    },
    clickTag(key) {
      this.role = key;
    },
    cut() {
      this.$store.commit("login/CUT", 3);
    },
  },
  computed: mapState(["userInfo"]),
  mounted() {
    let index = 0; //截取图片的次数
    let dsq = null;
    let _this = this;
    //开启/关闭 摄像头
    $("#openBtn").click(function () {
      if ($("#openBtn").text() == "开启摄像头") {
        $("#openBtn").hide();
        $("#exit").hide();
        //开启摄像头
        openMedia();
        $("button").text("关闭摄像头");
        //     随意截取5张图片
        dsq = setInterval(function () {
          index++;
          getPhone();
          _this.$message(`第${index}次验证`);
          if (index == 5) {
            clearInterval(dsq);
            closeMedia();
            $("button").text("开启摄像头");
            _this.$message("人脸核验失败，请重试");

            _this.cut();
          }
        }, 2000);
      } else {
        $("button").text("开启摄像头");
        clearInterval(dsq);
        closeMedia();
      }
    });

    //开启摄像头
    const openMedia = function () {
      let constraints = {
        video: { width: 913, height: 500 },
        audio: false,
      };
      //获得video摄像头
      let video = document.getElementById("video");
      let promise = navigator.mediaDevices.getUserMedia(constraints);
      promise.then((mediaStream) => {
        // mediaStreamTrack = typeof mediaStream.stop === 'function' ? mediaStream : mediaStream.getTracks()[1];
        window.mediaStreamTrack = mediaStream.getVideoTracks();
        video.srcObject = mediaStream;
        video.play();
      });
    };

    // 关闭摄像头
    const closeMedia = function () {
      let stream = document.getElementById("video").srcObject;
      let tracks = stream.getTracks();
      tracks.forEach(function (track) {
        track.stop();
      });
      document.getElementById("video").srcObject = null;
    };

    //截取摄像头里的图片 ：暂时无法实现 获取摄像头里面的人脸。
    //只能通过定时器：来定时截取摄像头里面的照片 然后提交给后台测试是否通过人脸识别

    const getPhone = function () {
      let video = document.getElementById("video");
      let canvas = document.getElementById("canvas");
      let ctx = canvas.getContext("2d");
      ctx.drawImage(video, 0, 0, 300, 150);
      let img = document.getElementById("canvas").toDataURL();
      // 获取截取图片的base64编码
      let base64 = img.split(",")[1];
      let formData = new FormData()
      formData.append("file", base64)
      axios.post("/api/fece/login", formData).then((res) => {
        let id = JSON.parse(res.data.data).result.user_list[0].user_id
        let score = JSON.parse(res.data.data).result.user_list[0].score
        if (score > 60) {
          axios.get(`/api/face/byid?id=${id}`).then(res => {
            let resData = res.data.data;
            console.log(resData);
            if (resData != null) {
              switch (resData.role) {
                case "0": //管理员
                  Vue.$cookies.set("cname", resData.adminName);
                  Vue.$cookies.set("cid", resData.adminId);
                  Vue.$cookies.set("role", 0);
                  Vue.$router.push({ path: "/index" }); //跳转到首页
                  break;
                case "1": //教师
                  Vue.$cookies.set("cname", resData.teacherName);
                  Vue.$cookies.set("cid", resData.teacherId);
                  Vue.$cookies.set("role", 1);
                  Vue.$router.push({ path: "/index" }); //跳转到教师用户
                  break;
                case "2": //学生
                  Vue.$cookies.set("cname", resData.studentName);
                  Vue.$cookies.set("cid", resData.studentId);
                  Vue.$router.push({ path: "/student" });
                  break;
              }
            }
          })
        }
      });
      // face/login/{id}
      // $.ajax({
      //   url: "/api/fece/login", //这里必须要使用post 因为base64编码的长度过长
      //   type: "post",
      //   //这里的list：表示从哪个小组查询人脸、可以根据项目需求，决定是否写死或写活
      //   data: { base64: base64 },
      //   dataType: "json",
      //   success: function (data) {
      //     let score = data.result.user_list[0].score;

      //     console.log(data);

      //     if (score > 80) {
      //       clearInterval(dsq);
      //       closeMedia();
      //       $("button").text("开启摄像头");
      //       alert("登录成功，你的用户id为" + data.result.user_list[0].user_id);
      //     }
      //   },
      // });
    };
  },
};
</script>

<style lang="less" scoped>
.remind {
  border-radius: 4px;
  padding: 10px 20px;
  display: flex;
  position: fixed;
  right: 20px;
  bottom: 50%;
  flex-direction: column;
  color: #606266;
  background-color: #fff;
  border-left: 4px solid #409eff;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

.container {
  margin-bottom: 32px;
}

.container .el-radio-group {
  margin: 30px 0px;
}

a:link {
  color: #ff962a;
  text-decoration: none;
}

#login {
  font-size: 14px;
  color: #000;
  background-color: #fff;
}

#login .bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  overflow-y: auto;
  height: 100%;
  background: url("../../../../assets/img/loginbg.png") center top / cover no-repeat;
  background-color: #b6bccdd1 !important;
}

#login .main-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

#login .main-container .top {
  margin-top: 100px;
  font-size: 30px;
  color: #ff962a;
  display: flex;
  justify-content: center;
}

#login .top .icon-kaoshi {
  font-size: 80px;
}

#login .top .title {
  margin-top: 20px;
}

#login .bottom {
  display: flex;
  justify-content: center;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

#login .bottom .title {
  text-align: center;
  font-size: 30px;
}

.bottom .container .title {
  margin: 30px 0px;
}

.bottom .submit .row-login {
  width: 100%;
  background-color: #04468b;
  border-color: #04468b;
  margin: 20px 0px 10px 0px;
  padding: 15px 20px;
}

.bottom .submit {
  display: flex;
  justify-content: center;
}

.footer {
  margin-top: 50px;
  text-align: center;
}

.footer .msg1 {
  font-size: 18px;
  color: #fff;
  margin-bottom: 15px;
}

.footer .msg2 {
  font-size: 14px;
  color: #e3e3e3;
  margin-top: 70px;
}

.bottom .options {
  margin-bottom: 40px;
  color: #ff962a;
  display: flex;
  justify-content: space-between;
}

.bottom .options>a {
  color: #ff962a;
}

.bottom .options .register span:nth-child(1) {
  color: #8c8c8c;
}

.code-input {
  width: 80px;
}

.code-btn {
  width: 120px;
}

.wrap {
  width: 100%;
  height: 100%;
  position: relative;
}

video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transform: rotateY(180deg);
  // object-fit: fill;
}

#openBtn {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 99;
}

canvas {
  width: 100%;
  height: 334.14px;
  //display: none;
}

#exit {
  position: absolute;
  top: 8px;
  left: 0;
  z-index: 99;
}
</style>
